<template>
  <div>
    <Upload
        type="drag"
        accept=".doc,.docx,.txt"
        :before-upload="handleUpload"
        :format="upFormat"
        :on-format-error="onFormatError"
        action="">
      <div style="padding: 5px 0; height: 90px;">
        <Icon type="ios-cloud-upload" size="30" style="color: #3399ff"></Icon>
        <p>上传案例文件（支持docx、doc、txt文件）</p>
      </div>
    </Upload>
    <Input v-model="content" debounce="500" type="textarea" :rows="10" placeholder="输入案件信息……"/>
    <div id="button-holder">
      <Button type="success" :loading="loading" @click="analyze">
        <span v-if="!loading">标注案例</span>
        <span v-else>分析中</span>
      </Button>
      <Button type="error" @click="clearContent">清空内容</Button>
    </div>
  </div>
</template>

<script>
import {uploadFileAPI} from "@/api/uploadFile";
import {analyzeAPI} from "@/api/analyzeCase";

export default {
  name: "UploadCase",
  computed: {
    content: {
      get() {
        return this.$store.state.content
      },
      set(val) {
        this.$store.commit('setContent', val)
      }
    },
    autoLabeled: {
      get() {
        return this.$store.state.autoLabeled
      },
      set(val) {
        this.$store.commit('setAutoLabeled', val)
      }
    },
    labels: {
      get() {
        return this.$store.state.labels
      },
      set(val) {
        this.$store.commit('setLabels', val)
      }
    },
  },
  data() {
    return {
      upFormat: ['txt', 'doc', 'docx'],
      loading: false,
      prevHash: 0,
    }
  },
  methods: {
    getHash(str) {
      let hash = 1315423911, i, ch;
      for (i = str.length - 1; i >= 0; i--) {
        ch = str.charCodeAt(i);
        hash ^= ((hash << 5) + ch + (hash >> 2));
      }
      return (hash & 0x7FFFFFFF);
    },

    analyze() {
      this.loading = true
      if (!(this.content.trim() === '')) {
        let curHash = this.getHash(this.content)
        if (this.prevHash === 0 || !(curHash === this.prevHash)) {
          this.prevHash = curHash

          let _this = this
          let formData = new FormData()
          formData.append('content', this.content)

          analyzeAPI(
              formData,
              (res) => {
                this.$Message['success']({
                  background: true,
                  content: '分析完成'
                })
                console.log('analyze succeeded', res)
                this.$store.commit('setAutoLabeled', res.autoLabeled)
                this.$store.commit('setLabels', res.labels)
              }, () => {
                this.$Message['error']({
                  background: true,
                  content: '分析失败'
                })
              }, () => {
                _this.loading = false
              }
          )
        } else {
          this.$Message['warning']({
            background: true,
            content: '内容无变化'
          })
          this.loading = false
        }
      } else {
        this.prevHash = 0
        this.$Message['warning']({
          background: true,
          content: '内容为空'
        })
        this.loading = false
      }
    },

    clearContent() {
      this.$store.commit('setContent', '')
      this.prevHash = 0
    },

    handleUpload(file) {
      this.upload(file)
      return false
    },

    onFormatError(file) {
      console.log('format error', file)
      this.$Message["error"]({
        background: true,
        content: '文件格式错误，请重新上传'
      });
    },

    upload(file) {
      console.log(file)

      let _this = this
      let formData = new FormData()
      formData.append('file', file)

      uploadFileAPI(
          formData,
          function (content) {
            console.log("upload succeeded");
            _this.$store.commit('setContent', content)
            _this.prevHash = 0
          },
          function (error) {
            console.log(error);
            _this.$store.commit('setContent', '')
            _this.$Message["error"]({
              background: true,
              content: '文件上传失败'
            });
          }, () => {
          }
      );
    }
  }
}
</script>

<style scoped>
p {
  font-size: 0.7em;
}

#button-holder {
  width: 100%;
}

#button-holder Button {
  margin: 0 20px;
}
</style>